import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description: UDP回显服务——客户端
 */
public class UdpEchoClient {
    //创建一个socket实例
    private DatagramSocket socket = null;
    //指定服务器的IP和端口号
    private String serverIP;
    private int serverPort;

    public UdpEchoClient(String serverIP, int serverPort) throws SocketException {
        this.socket = new DatagramSocket();
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }

    //构造方法，客户端直接可以让系统分配一个空闲端口即可
    public UdpEchoClient() throws SocketException {
        this.socket = new DatagramSocket();
    }

    //启动服务器
    public void start() throws IOException {
        System.out.println("启动服务器！");
        Scanner scanner = new Scanner(System.in);
        while(true) {
            // 1. 先从控制台读取用户输入的字符串
            System.out.print("请输入请求内容-> ");
            String request = scanner.nextLine();
            // 2. 把输入的字符串构造成一个UDP请求并发送
            // 需要指明把数据发给谁
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIP), serverPort);

            socket.send(requestPacket);
            // 3. 从服务器读取响应数据，并解析
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength(), "UTF-8");
            // 4. 把响应结果显示到控制台上
            System.out.printf("req: %s resp: %s\n", request, response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1", 9090);
        udpEchoClient.start();
    }
}
